package com.mkyong.common.controller;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

import com.mkyong.common.persistence.Employee;

@Controller
public class HelloController {

	/**
	 * Si tú creas nuevas instancias de objetos, estos no son monitoreados por
	 * Spring, lo cual genera que sus dependencias no sean inyectadas, tal y
	 * como se explica en: http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null La primera respuesta
	 */
	@Autowired
	private ManageEmployee manage;

	@RequestMapping(value = "/employee", method = RequestMethod.GET)
	public ModelAndView employee() {
		return new ModelAndView("employee", "command", new Employee());
	}
	
	@RequestMapping(value = "/editEmployee", method = RequestMethod.GET)
	public ModelAndView editEmployee(@RequestParam("id") int id) {
		Employee employee = manage.getEmployee(id);
		return new ModelAndView("editEmployee", "command", employee);
	}

	@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
	public String addEmployee(@ModelAttribute("SpringWeb") Employee employee,
			ModelMap model) {
		manage.addEmployee(employee);
		model.addAttribute(employee);
		return "result";
	}
	
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String editEmployee(@ModelAttribute("SpringWeb") Employee employee,
			ModelMap model) {
		manage.updateEmployee(employee);
		model.addAttribute(employee);
		return "result";
	}
	
	@RequestMapping(value = "/deleteEmployee", method = RequestMethod.GET)
	public String deleteEmployee(@RequestParam("id") int id,
			ModelMap model) {
		boolean isDone =  false;
		String message = "";
		isDone = manage.deleteEmployee(id);
		message = (isDone)?"Employee deleted":"Employee can't be delete";
		List<Employee> employees = manage.listEmployees();
		model.addAttribute("employees",employees);
		model.addAttribute("message","Employee deleted");
		return "listEmployee";
	}
	
	@RequestMapping(value ="/listEmployee", method = RequestMethod.GET)
	public String listEmployee(ModelMap model){
		List<Employee> employees = manage.listEmployees();
		model.addAttribute("employees",employees);
		return "listEmployee";
	}

	@RequestMapping(value = "/welcome", method = RequestMethod.GET)
	public String printWelcome(ModelMap model) {

		model.addAttribute("message", "Spring 3 MVC Hello World");
		return "hello";

	}

}